package com.alan.swagger2.controller;

import com.alan.swagger2.bean.DetailDTO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping(value = "file")
@Slf4j
public class FileController  {

	/**
	 * json返回与文件下载共存方法
	 * @param response
	 * @param flag
	 * @return
	 */
	@ApiIgnore
	@RequestMapping(value = "downloadTest",produces = {"application/json;charset=utf-8"})
	@ResponseBody
	public String hello(HttpServletRequest request, HttpServletResponse response,String flag){
		String res = null;
		try {
			if("1".equals(flag)){
				//实现 response.sendRedirect 功能
				response.setStatus(302);
				response.setHeader("Location","http://www.baidu.com");
//				response.sendRedirect("http://www.baidu.com");
			}else {
				res = "hello";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	@RequestMapping(value="uploadFile2",method=RequestMethod.POST)
	@ApiOperation(value="文件上传")
	@ResponseBody
	public DetailDTO<Info> uploadFile2(HttpServletRequest request, String name){
		log.info("文件上传");
		DetailDTO<Info> detailDTO = new DetailDTO<Info>(true);
		MultipartHttpServletRequest mulReq = (MultipartHttpServletRequest) request;
		MultipartFile file = null;
		Map<String, MultipartFile> filesMap = mulReq.getFileMap();
		if(null != filesMap){
			try {
				for (String key: filesMap.keySet()) {
					file = filesMap.get(key);
					String templateImagePath = "C:/Temp/" + key +   System.currentTimeMillis() +".jpg";
					File templateFile = new File(templateImagePath);
					file.transferTo(templateFile);
				}
			}catch (Exception e) {
				log.error("保存图片失败：{}",e);
				detailDTO.setStatus(false);
				detailDTO.setErrorCode("01");
				detailDTO.setErrorMessage("保存图片错误！");
				return detailDTO;
			}
		}
		detailDTO.setStatus(true);
		detailDTO.setErrorCode("200");
		detailDTO.setUserMessage("保存图片成功！");
		return detailDTO;
	}

	@RequestMapping(value="uploadFile",method=RequestMethod.POST)
	@ApiOperation(value="文件上传")
	@ResponseBody
	public DetailDTO<Info> uploadFile(HttpServletRequest request, String name){
		log.info("文件上传");
		DetailDTO<Info> detailDTO = new DetailDTO<Info>(true);
		MultipartHttpServletRequest mulReq = (MultipartHttpServletRequest) request;
		MultipartFile file = null;
		Map<String, MultipartFile> filesMap = mulReq.getFileMap();
		if(null != filesMap){
			//这里应该是文件名
			String key = "resource";
			file = filesMap.get(key);
			if(null == file){
				detailDTO.setStatus(false);
				detailDTO.setErrorMessage("保存图片错误！");
				return detailDTO;
			}
		}
		String templateImagePath = "C:/Temp" + "/Test" +   System.currentTimeMillis() +".jpg";
		File templateFile = new File(templateImagePath);
		try {
			file.transferTo(templateFile);
		}catch (Exception e) {
			log.error("保存图片异常：{}",e);
			detailDTO.setStatus(false);
			detailDTO.setErrorCode("01");
			detailDTO.setErrorMessage("保存图片错误！");
			return detailDTO;
		}
		detailDTO.setStatus(true);
		detailDTO.setErrorCode("200");
		detailDTO.setUserMessage("保存图片成功！");
		return detailDTO;
	}
	
	private class Info {
		public String name;
		public String url;
	}
	
	/**
     * 文件下载
     * @Description: 
     * @param fileName
     * @param request
     * @param response
     * @return
     */
	@RequestMapping(value="download",method=RequestMethod.GET)
	@ApiOperation(value="文件下载")
	public String downloadFile(@RequestParam("fileName") String fileName, HttpServletRequest request,
			HttpServletResponse response) {
		if (fileName != null) {
			String realPath = request.getSession().getServletContext().getRealPath("download/");
			File file = new File(realPath, fileName);
			if (file.exists()) {
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}
	
	
}
